package com.zch.starter.metrics.prometheus.springboot.starter.instance.actuator;

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicLong;

/**
 * 简单的监控检测（线上够用了）
 * springboot 自带的 actuate 健康检测
 * //每次有第三方应用探测 调用http://localhost:9090/actuator/health 健康接口的时候都会触发health()方法
 */
public class LivenessHealthIndicator implements HealthIndicator {
    // 健康时间
    private final AtomicLong lastHealthTime = new AtomicLong(System.currentTimeMillis());

    /**
     * 触发来源
     * 1 健康探测
     * 2 服务主动的健康心跳
     * @return
     */
    @Override
    public Health health() {
        long now = System.currentTimeMillis();
        lastHealthTime.set(now);
        return Health.up().build();
    }

    // 获取最新的健康时间
    public long getLastHealthTime() {
        return lastHealthTime.get();
    }

    // 获取最新的健康时间延迟(秒)
    public long getLastHealthDelaySecond() {
        long now = System.currentTimeMillis();
        return (now - lastHealthTime.get())/1000;
    }
}
